package com.sendpo.zjx.sendpo.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.broadcastreceiver.LoginWxBroadcastReceiver;
import com.sendpo.zjx.sendpo.domain.UserDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/7/14.
 */

public class LoginActivity extends AppCompatActivity {
    private static final int REQUEST_CODE_REQUEST_PERMISSION = 10101;


    public boolean isLoading = false;
    public Tencent tencent;
    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.index_head)
    RelativeLayout indexHead;
    @BindView(R.id.user_iv)
    ImageView userIv;
    @BindView(R.id.edit_iphone)
    EditText editIphone;
    @BindView(R.id.accout_rl)
    RelativeLayout accoutRl;
    @BindView(R.id.password_iv)
    ImageView passwordIv;
    @BindView(R.id.edit_password)
    EditText editPassword;
    @BindView(R.id.password_rl)
    RelativeLayout passwordRl;
    @BindView(R.id.forgetpassword_bt)
    TextView forgetpasswordBt;
    @BindView(R.id.loginbt)
    RelativeLayout loginbt;
    @BindView(R.id.wx_loginbt)
    RelativeLayout wxLoginbt;
    @BindView(R.id.qq_img)
    ImageView qqImg;
    @BindView(R.id.qq_loginbt)
    RelativeLayout qqLoginbt;

    private IWXAPI iwxapi;
    Intent intent = null;
    LoginWxBroadcastReceiver receiver;
    private Dialog loadingdialog = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        initComponent();

    }

    public void initComponent() {
        loadingdialog = new Dialog(this);
        loadingdialog.setContentView(R.layout.dialog_loading);
        loadingdialog.setCanceledOnTouchOutside(false);
        loadingdialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        tencent = Tencent.createInstance(HttpUrl.QQ_KEY, this.getApplicationContext());
        receiver = new LoginWxBroadcastReceiver(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(LoginWxBroadcastReceiver.ACTION_NAME);
        registerReceiver(receiver, filter);
//        iwxapi= WXAPIFactory.createWXAPI(this, HttpUrl.WX_KEY, true);
//        iwxapi.registerApp(HttpUrl.WX_KEY);
  //      initRequestPermission();
    }


    //手机登录
    public void loginIphone(String userIphone, String userPassword) {
        if (!isLoading) {
            loadingdialog.show();
            isLoading = true;
            Map<String, String> map = new HashMap<>();
            map.put("userIphone", userIphone);
            map.put("userPassword", userPassword);
            Xutils.POST(HttpUrl.loginbyiphone, map, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    loadingdialog.dismiss();
                    isLoading = false;
                    Gson gson = new Gson();

                    UserDomain userDomain = gson.fromJson(result, UserDomain.class);

                    switch (userDomain.getState()) {
                        case HttpCode.LOGIN_SUCCESS:
                            boolean isSuccess = Xutils.save(LoginActivity.this.getApplication(), userDomain.getData());
                            Toast.makeText(getApplicationContext(),"登录成功", Toast.LENGTH_SHORT).show();
                            finish();
                            break;
                        case HttpCode.LOGIN_ERROR:
                            Toast.makeText(getApplicationContext(), userDomain.getMessage(), Toast.LENGTH_SHORT).show();

                            break;
                        case HttpCode.THROW:

                            Toast.makeText(getApplicationContext(), userDomain.getMessage(), Toast.LENGTH_SHORT).show();
                            break;
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    loadingdialog.dismiss();
                    isLoading = false;
                    Toast.makeText(getApplicationContext(), "网络有误", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (receiver != null) {
            unregisterReceiver(receiver);
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            //QQ验证登录
            case Constants.REQUEST_LOGIN:
                Tencent.onActivityResultData(requestCode, resultCode, data, new QQLoginListener());
                break;
        }

    }

    //QQ登录监听
    public class QQLoginListener implements IUiListener {
        @Override
        public void onComplete(Object o) {
            if (o == null) {
                return;
            }
            JSONObject jo = (JSONObject) o;
            try {
                int ret = jo.getInt("ret");
                if (ret == 0) {
                    String openid = jo.getString("openid");
                    String access_token = jo.getString("access_token");
                    String expires_in = jo.getString("expires_in");
                    tencent.setOpenId(openid);
                    tencent.setAccessToken(access_token, expires_in);
                    UserInfo qqInfo = new UserInfo(LoginActivity.this, tencent.getQQToken());
                    qqInfo.getUserInfo(new QQgetUserListener(openid));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError uiError) {
            Toast.makeText(getApplicationContext(), "网络有误", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel() {
        }
    }

    //得到QQ用户信息
    public class QQgetUserListener implements IUiListener {
        String openid = "";

        public QQgetUserListener(String openid) {
            this.openid = openid;
        }

        @Override
        public void onComplete(Object o) {
            if (o == null) {
                return;
            }
            JSONObject jo = (JSONObject) o;
            System.out.println("***********jo:" + jo.toString());
            String path = "";
            String nickname = "";
            String gender = "男";
            try {
                nickname = jo.getString("nickname");
                gender = jo.getString("gender");
                path = jo.getString("figureurl_qq_2");
                System.out.println("****************昵称" + nickname + openid);
                System.out.println("****************头像" + path);
                System.out.println("****************性别" + gender);
                Map<String, String> map = new HashMap<>();
                map.put("userQqid", openid);
                map.put("userName", nickname);
                map.put("userProvince", "");
                map.put("userCity", "");
                map.put("userArea", "");
                map.put("userAddress", "");
                map.put("userLongitude", "");
                map.put("userLatitude", "");
                loadingdialog.show();
                isLoading = true;
                Xutils.POST(HttpUrl.loginbyqq, map, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        Gson gson = new Gson();
                        loadingdialog.dismiss();
                        isLoading = false;
                        UserDomain userDomain = gson.fromJson(result, UserDomain.class);
                        switch (userDomain.getState()) {
                            case HttpCode.LOGIN_SUCCESS:
                                boolean isSuccess = Xutils.save(LoginActivity.this.getApplication(), userDomain.getData());
                                Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
                                finish();
                                break;
                            case HttpCode.LOGIN_ERROR:
                                Toast.makeText(getApplicationContext(), userDomain.getMessage(), Toast.LENGTH_SHORT).show();

                                break;
                            case HttpCode.THROW:
                                Toast.makeText(getApplicationContext(), userDomain.getMessage(), Toast.LENGTH_SHORT).show();

                                break;
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        loadingdialog.dismiss();
                        isLoading = false;
                        Toast.makeText(getApplicationContext(), "网络有误", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });


            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError uiError) {

        }

        @Override
        public void onCancel() {

        }
    }


    //QQ登录
    public void qqLogin() {
        Toast.makeText(getApplicationContext(), "正在打开QQ登录", Toast.LENGTH_SHORT).show();
        tencent.login(this, "all", new QQLoginListener());
    }

    //微信登录
    public void wxlogin() {
        Toast.makeText(getApplicationContext(), "正在打开微信登录", Toast.LENGTH_SHORT).show();
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wxchat_login";
        iwxapi.sendReq(req);//执行完毕这句话之后，会在WXEntryActivity回调
    }

    public void createwxlogin(String openid, String nickname) {
        System.out.println("***********" + openid);
        Map<String, String> map = new HashMap<>();
        map.put("userWxid", openid);
        map.put("userName", nickname);
        map.put("userProvince", "");
        map.put("userCity", "");
        map.put("userArea", "");
        map.put("userAddress", "");
        map.put("userLongitude", "");
        map.put("userLatitude", "");
        loadingdialog.show();
        isLoading = true;
        Xutils.POST(HttpUrl.iphoneloginwxin, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                loadingdialog.dismiss();
                isLoading = false;
                Gson gson = new Gson();
                UserDomain userDomain = gson.fromJson(result, UserDomain.class);
                switch (userDomain.getState()) {
                    case HttpCode.LOGIN_SUCCESS:
                        boolean isSuccess = Xutils.save(LoginActivity.this.getApplication(), userDomain.getData());
                        Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
                        finish();
                        break;
                    case HttpCode.LOGIN_ERROR:
                        Toast.makeText(getApplicationContext(), userDomain.getMessage(), Toast.LENGTH_SHORT).show();
                        break;
                    case HttpCode.THROW:
                        Toast.makeText(getApplicationContext(), userDomain.getMessage(), Toast.LENGTH_SHORT).show();

                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                loadingdialog.dismiss();
                isLoading = false;
                Toast.makeText(getApplicationContext(), "网络有误", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    public void initRequestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_WIFI_STATE
        }, REQUEST_CODE_REQUEST_PERMISSION);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_REQUEST_PERMISSION:

                break;
        }
    }


    @OnClick({R.id.backbt,R.id.loginbt, R.id.forgetpassword_bt, R.id.qq_loginbt, R.id.wx_loginbt,R.id.register_bt})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;
            case R.id.register_bt:
                Tools.redirectActivity(this,ResgiterActivity.class);
                break;
            case R.id.loginbt:
                if(isLoading){
                    return;
                }
                if(TextUtils.isEmpty(editIphone.getText().toString().trim())){
                    Toast.makeText(getApplicationContext(),"手机号不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(TextUtils.isEmpty(editPassword.getText().toString().trim())){
                    Toast.makeText(getApplicationContext(),"密码不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                loginIphone(editIphone.getText().toString().trim(),editPassword.getText().toString().trim());
                break;

            case R.id.forgetpassword_bt:
                Tools.redirectActivity(this, ForgetPassActivity.class);
                break;
            case R.id.qq_loginbt:
                qqLogin();
                break;
            case R.id.wx_loginbt:
                wxlogin();
                break;


        }

    }
}
